import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../res/color_res.dart';
import '../../../routes/app_pages.dart';
import '../controllers/home_detail_controller.dart';

class HomeDetailView extends GetView<HomeDetailController> {
  const HomeDetailView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('文章详情'),
        centerTitle: true,
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0.5,
        actions: [
          // 修改按钮
          IconButton(
            onPressed: () => _editPost(),
            icon: const Icon(
              Icons.edit_outlined,
              color: Color(0xFF3561B9),
            ),
            tooltip: '修改文章',
          ),
          // 删除按钮
          Obx(() => IconButton(
                onPressed: controller.isDeletingPost.value
                    ? null
                    : controller.deletePost,
                icon: controller.isDeletingPost.value
                    ? SizedBox(
                        width: 20.w,
                        height: 20.w,
                        child: const CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
                        ),
                      )
                    : const Icon(
                        Icons.delete_outline,
                        color: Colors.red,
                      ),
                tooltip: '删除文章',
              )),
        ],
      ),
      body: Container(
        color: const Color(pageBg),
        child: Obx(() {
          if (controller.isLoadingDetail.value &&
              controller.postDetail.value == null) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }

          return Column(
            children: [
              // 滚动内容区域
              Expanded(
                child: CustomScrollView(
                  slivers: [
                    // 文章详情部分
                    SliverToBoxAdapter(
                      child: _buildPostDetail(),
                    ),

                    // 评论标题
                    SliverToBoxAdapter(
                      child: _buildCommentHeader(),
                    ),

                    // 评论列表
                    _buildCommentList(),

                    // 底部间距
                    SliverToBoxAdapter(
                      child: SizedBox(height: 16.w),
                    ),
                  ],
                ),
              ),

              // 评论输入区域
              _buildCommentInput(),
            ],
          );
        }),
      ),
    );
  }

  // 构建文章详情
  Widget _buildPostDetail() {
    final post = controller.postDetail.value;
    if (post == null) {
      return Container(
        height: 200.h,
        margin: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: const Center(
          child: Text('文章加载失败'),
        ),
      );
    }

    return Container(
      margin: EdgeInsets.all(16.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文章标题
          Text(
            post.title ?? '',
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
              height: 1.3,
            ),
          ),
          SizedBox(height: 12.w),

          // 发布时间和状态
          Row(
            children: [
              Icon(
                Icons.access_time,
                size: 16.r,
                color: Colors.grey[500],
              ),
              SizedBox(width: 4.w),
              Text(
                controller.formatTime(post.createTime),
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[500],
                ),
              ),
              const Spacer(),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.w),
                decoration: BoxDecoration(
                  color: post.state == 1
                      ? Colors.green.withOpacity(0.1)
                      : Colors.grey.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4.r),
                ),
                child: Text(
                  post.state == 1 ? '已发布' : '草稿',
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: post.state == 1 ? Colors.green : Colors.grey,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 20.w),

          // 文章内容
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Text(
              post.content ?? '',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.black87,
                height: 1.6,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建评论标题
  Widget _buildCommentHeader() {
    return Container(
      margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 8.w),
      child: Row(
        children: [
          Icon(
            Icons.comment_outlined,
            size: 20.r,
            color: Colors.grey[700],
          ),
          SizedBox(width: 8.w),
          Text(
            '评论',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          SizedBox(width: 8.w),
          Obx(() => Text(
                '(${controller.commentTotalCount.value})',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[600],
                ),
              )),
        ],
      ),
    );
  }

  // 构建评论列表
  Widget _buildCommentList() {
    return Obx(() {
      if (controller.isLoadingComments.value &&
          controller.commentList.isEmpty) {
        return SliverToBoxAdapter(
          child: Container(
            height: 100.h,
            child: const Center(
              child: CircularProgressIndicator(),
            ),
          ),
        );
      }

      if (controller.commentList.isEmpty) {
        return SliverToBoxAdapter(
          child: Container(
            height: 100.h,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: const Center(
              child: Text(
                '暂无评论',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.grey,
                ),
              ),
            ),
          ),
        );
      }

      return SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            final comment = controller.commentList[index];
            return _buildCommentItem(comment);
          },
          childCount: controller.commentList.length,
        ),
      );
    });
  }

  // 构建评论项
  Widget _buildCommentItem(comment) {
    return Container(
      margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 8.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 评论者信息
          Row(
            children: [
              CircleAvatar(
                radius: 16.r,
                backgroundColor: const Color(0xFF3561B9),
                child: Text(
                  (comment.userName ?? '匿名').substring(0, 1),
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      comment.userName ?? '匿名用户',
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                    ),
                    Text(
                      controller.formatTime(comment.createTime),
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.grey[500],
                      ),
                    ),
                  ],
                ),
              ),
              // 删除按钮
              Obx(() => IconButton(
                    onPressed: controller.isCommentDeleting(comment.id ?? 0)
                        ? null
                        : () => controller.deleteComment(comment.id ?? 0),
                    icon: controller.isCommentDeleting(comment.id ?? 0)
                        ? SizedBox(
                            width: 16.w,
                            height: 16.w,
                            child: const CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor:
                                  AlwaysStoppedAnimation<Color>(Colors.red),
                            ),
                          )
                        : Icon(
                            Icons.delete_outline,
                            color: Colors.red[400],
                            size: 18.sp,
                          ),
                    tooltip: '删除评论',
                    padding: EdgeInsets.all(4.w),
                    constraints: BoxConstraints(
                      minWidth: 32.w,
                      minHeight: 32.w,
                    ),
                  )),
            ],
          ),
          SizedBox(height: 12.w),

          // 评论内容
          Text(
            comment.content ?? '',
            style: TextStyle(
              fontSize: 15.sp,
              color: Colors.black87,
              height: 1.4,
            ),
          ),
        ],
      ),
    );
  }

  // 构建评论输入区域
  Widget _buildCommentInput() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, -1),
          ),
        ],
      ),
      child: SafeArea(
        child: Row(
          children: [
            // 输入框
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: TextField(
                  controller: controller.commentController,
                  decoration: InputDecoration(
                    hintText: '写下你的评论...',
                    hintStyle: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 14.sp,
                    ),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 16.w,
                      vertical: 10.w,
                    ),
                  ),
                  style: TextStyle(fontSize: 14.sp),
                  maxLines: 3,
                  minLines: 1,
                ),
              ),
            ),

            SizedBox(width: 12.w),

            // 发送按钮
            Obx(() => GestureDetector(
                  onTap: controller.isSubmittingComment.value
                      ? null
                      : controller.submitComment,
                  child: Container(
                    width: 40.w,
                    height: 40.w,
                    decoration: BoxDecoration(
                      color: controller.isSubmittingComment.value
                          ? Colors.grey[400]
                          : const Color(0xFF3561B9),
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    child: controller.isSubmittingComment.value
                        ? Center(
                            child: SizedBox(
                              width: 16.w,
                              height: 16.w,
                              child: const CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor:
                                    AlwaysStoppedAnimation<Color>(Colors.white),
                              ),
                            ),
                          )
                        : Icon(
                            Icons.send,
                            color: Colors.white,
                            size: 18.r,
                          ),
                  ),
                )),
          ],
        ),
      ),
    );
  }

  // 编辑文章
  void _editPost() async {
    final post = controller.postDetail.value;
    if (post == null) {
      Get.snackbar('错误', '文章信息不完整');
      return;
    }

    // 跳转到编辑页面
    final result = await Get.toNamed(
      Routes.EDIT_POST,
      arguments: {
        'postId': controller.postId,
        'title': post.title ?? '',
        'content': post.content ?? '',
        'state': post.state ?? 1,
      },
    );

    // 处理编辑结果
    if (result != null && result['success'] == true) {
      // 更新详情页数据
      controller.updatePostDetail(
        title: result['title'],
        content: result['content'],
        state: result['state'],
      );
    }
  }
}
